﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Reporting.WebForms;
using System.Data;
using Runda.CMS.Bll;
using Runda.CMS.Common.Entity;
using Runda.CMS.Common.Utility;
using System.Text;
using Telerik.Web.UI;

namespace Runda.CMS.Portal.SalesManage
{
    public partial class QueryBillsEx : BasePage
    {
        
        public string SortString
        {
            get
            {
                if (ViewState["SortString"] == null)
                {
                    ViewState["SortString"] = "customername";
                }

                return ViewState["SortString"].ToString();
            }
            set { ViewState["SortString"] = value; }
        }

        

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DataTable dt = new BudgetBll().Companylist(base.CurrentUserID.ToString());
                ddlCompany.DataSource = dt;
                ddlCompany.DataTextField = "Departmentname";
                ddlCompany.DataValueField = "Departmentname";
                ddlCompany.DataBind();
                ddlCompany.Items.Add(new ListItem("--不限--", "0"));
                ddlCompany.SelectedValue = "0";


                if (ddlCompany.SelectedValue != "0")
                {
                    dt = new BudgetBll().Departmentlist(base.CurrentUserID.ToString(), ddlCompany.SelectedValue.ToString());

                    ddlDept.DataSource = dt;
                    ddlDept.DataTextField = "Departmentname";
                    ddlDept.DataValueField = "Departmentname";
                    ddlDept.DataBind();
                    ddlDept.Items.Add(new ListItem("--不限--", "0"));
                    ddlDept.SelectedValue = "0";
                }
                BindGrid(1);
                Calculate();
                LoadRadTree("");
            }
        }

        private void LoadRadTree(string categoryCode)
        {
            string categoryGUID = "";
            //List<CtrtInstrumentCategoryEntity> categoryEntitys = new CtrtInstrumentCategoryBll().GetAll<CtrtInstrumentCategoryEntity>(" and parentGUID is null", "Order By categoryCode"); 
            DataTable dt = null;
            CtrtInstrumentCategoryBll bll = new CtrtInstrumentCategoryBll();
            dt = bll.GetInstrumentCategory("");//  and SUBSTRING(categorycode,1,2) in('01', '02')


            RadTreeView RadTreeProdType = RadComboBox_ProdType.Items[0].FindControl("RadTreeView_ProdType") as RadTreeView;
            //HtmlInputHidden Hidden_ProdTypeID = Page.FindControl("Text1") as HtmlInputHidden;
            //HtmlInputText txtSelectType = Page.FindControl("txt_SelectType") as HtmlInputText;
            if (RadTreeProdType != null)
            {
                RadTreeProdType.DataFieldID = "categoryGUID";
                RadTreeProdType.DataTextField = "categoryName";
                RadTreeProdType.DataValueField = "categoryGUID";
                RadTreeProdType.DataFieldParentID = "parentGUID";
                RadTreeProdType.DataSource = dt;
                RadTreeProdType.DataBind();
            }
            if (categoryCode != "")
            {
                Text1.Value = categoryCode;
                List<CtrtInstrumentCategoryEntity> categoryEntitys = new CtrtInstrumentCategoryBll().GetAll<CtrtInstrumentCategoryEntity>(" and parentGUID is null", "Order By categoryCode");

                if (categoryEntitys != null && categoryEntitys.Count > 0)
                {
                    categoryGUID = categoryEntitys[0].categoryCode;
                }

                if (categoryGUID != "")
                {
                    txt_SelectType.Value = RadTreeProdType.FindNodeByValue(categoryGUID).Text;

                    RadComboBox_ProdType.SelectedItem.Value = RadTreeProdType.FindNodeByValue(categoryGUID).Text;
                    RadComboBox_ProdType.SelectedItem.Text = RadTreeProdType.FindNodeByValue(categoryGUID).Text;
                    RadComboBox_ProdType.Text = RadTreeProdType.FindNodeByValue(categoryGUID).Text;
                }
            }

        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindGrid(1);
            Calculate();
        }

        protected void btnRefershBillInfo_Click(object sender, EventArgs e)
        {
            
        }

        protected void btnSaveSubItems_Click(object sender, EventArgs e)
        {
           
        }

        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            BindGrid(AspNetPager1.CurrentPageIndex);
            Calculate();
        }

        protected void btnRefersh_Click(object sender, EventArgs e)
        {
            BindGrid(AspNetPager1.CurrentPageIndex);
            Calculate();
        } 

        private void BindGrid(int pageindex)
        {
            string sb = getWhereClause();

            int RecordCount = 0;
            DataTable dt = new BillBll().QuerySalesBills(sb, SortString, AspNetPager1.PageSize, pageindex, out RecordCount);

            AspNetPager1.RecordCount = RecordCount;
            gridAccessoryList.DataSource = dt;
            gridAccessoryList.DataBind();
        }

        private void Calculate()
        {
            string sb = getWhereClause();

            BudgetBll bll = new BudgetBll();
            DataTable dt = bll.CalcbillAmountEx(sb);

            if (dt != null && dt.Rows.Count > 0)
            {
                lblTotal.Text = "合计：   金额："+string.Format("{0:N}", dt.Rows[0]["iNatMoney"])+"；价税合计："+string.Format("{0:N}", dt.Rows[0]["iNatSum"]);
 

            }
            else
            {

                lblTotal.Text = "";
            }
        }

        protected void gridAccessoryList_SortCommand(object source, Telerik.WebControls.GridSortCommandEventArgs e)
        {
            string OrderBy = e.SortExpression + " " + (e.NewSortOrder == Telerik.WebControls.GridSortOrder.Ascending ? "asc" : "desc");
            SortString = OrderBy;
            BindGrid(1);
            Calculate();
        }

        protected void btnQuery_Click(object sender, EventArgs e)
        {
            BindGrid(AspNetPager1.CurrentPageIndex);
            Calculate();
        }

        private string getWhereClause()
        { 
            StringBuilder sb = new StringBuilder();
            string beginDT, endDT;

            beginDT = ddlBudgetYear.SelectedValue + "-" + ddlBudgetMonth.SelectedValue + "-01";
            endDT = DataValid.Monthlastday(ddlBudgetYear.SelectedValue + "-" + ddlBudgetMonth1.SelectedValue + "-01");

            sb.Append(" and [dDate]  between '").Append(beginDT + "' and '").Append(endDT + "'");

            if (ddlStatPath1.SelectedValue == "1")
            {
                sb.Append(" and ((billUnit in(").Append("select DepartmentName from cms_sys_Department where iscompany = 1 and DepartmentID in(select DepartmentID from Cms_Sys_UserDepartment_DataRight where userid ='").Append(base.CurrentUserID.ToString()).Append("'))");
                sb.Append(" and CategoryCode in(").Append("select categoryCode from Cms_Ctrt_InstrumentCategory where categoryGUID in(select categoryGUID from Cms_sys_UserProductCategory where UserID ='").Append(base.CurrentUserID.ToString()).Append("')))");
                //sb.Append(" and (billUnit in(").Append("select DepartmentName from cms_sys_Department where iscompany = 1 and DepartmentID in(select DepartmentID from Cms_Sys_UserDepartment_DataRight where userid ='").Append(base.CurrentUserID.ToString()).Append("'))");
                //sb.Append(" or cCategoryCode in(").Append("select categoryCode from Cms_Ctrt_InstrumentCategory where PM='").Append(base.CurrentUserEntity.UserName.ToString()).Append("')");
                sb.Append(" or sales ='").Append(base.CurrentUserEntity.UserName.ToString()).Append("'");
                sb.Append(" or sales in(").Append("select username from vw_sysUser where DepartmentID in(select DepartmentID from Cms_Sys_UserDepartment_DataRight where userid ='").Append(base.CurrentUserID.ToString()).Append("')))");
            }
            else
            {
                sb.Append(" and ((BudgetUnit in(").Append("select DepartmentName from cms_sys_Department where iscompany = 1 and DepartmentID in(select DepartmentID from Cms_Sys_UserDepartment_DataRight where userid ='").Append(base.CurrentUserID.ToString()).Append("'))");
                sb.Append(" and CategoryCode in(").Append("select categoryCode from Cms_Ctrt_InstrumentCategory where categoryGUID in(select categoryGUID from Cms_sys_UserProductCategory where UserID ='").Append(base.CurrentUserID.ToString()).Append("')))");
                //sb.Append(" and (BudgetUnit in(").Append("select DepartmentName from cms_sys_Department where iscompany = 1 and DepartmentID in(select DepartmentID from Cms_Sys_UserDepartment_DataRight where userid ='").Append(base.CurrentUserID.ToString()).Append("'))");
                //sb.Append(" or cCategoryCode in(").Append("select categoryCode from Cms_Ctrt_InstrumentCategory where PM='").Append(base.CurrentUserEntity.UserName.ToString()).Append("')");
                sb.Append(" or sales ='").Append(base.CurrentUserEntity.UserName.ToString()).Append("'");
                sb.Append(" or sales in(").Append("select username from vw_sysUser where DepartmentID in(select DepartmentID from Cms_Sys_UserDepartment_DataRight where userid ='").Append(base.CurrentUserID.ToString()).Append("')))");
            }

            if (ddlStatPath2.SelectedValue == "1")
            { sb.Append(" and cCusCode in(select customerCode from cms_Bg_InnerCustomer)"); }
            else if (ddlStatPath2.SelectedValue == "2")
            { sb.Append(" and cCusCode not in(select customerCode from cms_Bg_InnerCustomer)"); }

            if (ddlCompany.SelectedValue != "0" && ddlStatPath1.SelectedValue == "1")
            {
                sb.Append(" and BillUnit='").Append(ddlCompany.SelectedValue.ToString()).Append("'");
            }

            if (ddlCompany.SelectedValue != "0" && ddlStatPath1.SelectedValue == "2")
            {
                sb.Append(" and BudgetUnit='").Append(ddlCompany.SelectedValue.ToString()).Append("'");
            }

            if (txtCustomerName.Text.Trim() != "")
            {
                sb.Append(" and CustomerName like '%").Append(txtCustomerName.Text.Trim()).Append("%'");
            }

            if (cBvcode.Text.Trim() != "")
            {
                sb.Append(" and cBVCode like '").Append(cBvcode.Text.Trim()).Append("%'");
            }

            string categoryCode = "";
            SystemBll bll = new SystemBll();
            if (Text1.Value != "")
            {
                Guid ID = new Guid(Text1.Value);
                CtrtInstrumentCategoryEntity instrmentEntity = bll.Get<CtrtInstrumentCategoryEntity>(ID);
                if (instrmentEntity != null)
                {
                    categoryCode = instrmentEntity.categoryCode;
                }
            }
            if (categoryCode != "") { sb.Append(" and categorycode like '").Append(categoryCode).Append("%'"); }

            if (ddlDept.SelectedValue != "0" && ddlDept.SelectedValue != "")
            {
                sb.Append(" and DepartmentName = '").Append(ddlDept.SelectedValue).Append("'");
            }

            if (txtSales.Text.Trim() != "")
            {
                sb.Append(" and sales like '").Append(txtSales.Text.Trim()).Append("%'");
            }
            return sb.ToString();

            
        }

        protected void gridContractItems_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem)
            {
                DataRowView dv = e.Item.DataItem as DataRowView;
                if (dv != null)
                {
                    RadNumericTextBox txtiNatSum_adjust = e.Item.FindControl("txtiNatSum_adjust") as RadNumericTextBox;
                    txtiNatSum_adjust.Value = Convert.ToDouble(dv["iNatSum_adjust"].ToString());
                }
            }
        }

        protected void btnExportExcel_Click(object sender, EventArgs e)
        {
            string Whereclause = getWhereClause();

            BillBll bll = new BillBll();

            DataTable dt = bll.GetSalesBills1_export(Whereclause);

            Export.Export2Excel(dt, "销售数据一览表", Page.Response);

        }

        protected void lnkbtnSubmit_Click(object sender, EventArgs e)
        {

            BudgetBll bll = new BudgetBll();
            bll.SubmmitBudget(ddlBudgetYear.SelectedValue.ToString(), base.CurrentUserEntity.UserName);
            

        }

        protected void lnkbtnCheck_Click(object sender, EventArgs e)
        {

            BudgetBll bll = new BudgetBll();
            //bll.CheckBudget(ddlBudgetYear.SelectedValue.ToString(), base.CurrentUserEntity.UserName);
        }

        protected void ddlCompany_SelectedIndexChanged(object sender, EventArgs e)
        {
            ddlDept.Items.Clear();
            DataTable dt = new BudgetBll().Departmentlist(base.CurrentUserID.ToString(), ddlCompany.SelectedValue.ToString());

            ddlDept.DataSource = dt;
            ddlDept.DataTextField = "Departmentname";
            ddlDept.DataValueField = "Departmentname";
            ddlDept.DataBind();
            ddlDept.Items.Add(new ListItem("--不限--", "0"));
            ddlDept.SelectedValue = "0";
        }
       
    }
}
